package com.flyco.modules.pms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flyco.common.util.HttpUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.bos.entity.BosTmComment;
import com.flyco.modules.pms.entity.PmsComment;
import com.flyco.modules.pms.mapper.PmsCommentMapper;
import com.flyco.modules.pms.model.PmsProductModel;
import com.flyco.modules.pms.service.IPmsCommentService;
import com.flyco.modules.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Description: 商品评价
 * @Author: flyco
 * @Date:   2020-02-27
 * @Version: V1.0
 */
@Slf4j
@Service
public class PmsCommentServiceImpl extends ServiceImpl<PmsCommentMapper, PmsComment> implements IPmsCommentService {
    @Autowired
    private PmsCommentMapper pmsCommentMapper;

    @Override
    public void syncFromBosTmComment() {
        StringBuilder url = new StringBuilder();
        url.append(ApiUtil.getSyncUrl());
        url.append("g/comment/getBosTmCommentWithUnSync");
        log.info("url:" + url.toString());
        String result = HttpUtil.getRequest(url.toString());
        log.info("result:" + result);
        if (oConvertUtils.isEmpty(result)) return;
        JSONObject resultObj = JSON.parseObject(result);
        if (oConvertUtils.isEmpty(resultObj) || oConvertUtils.isEmpty(resultObj.getJSONArray("result"))) return;
        JSONArray jsonArray = resultObj.getJSONArray("result");
        if (null == jsonArray || jsonArray.size() == 0) return;
        List<BosTmComment> comments = jsonArray.toJavaList(BosTmComment.class);
        //List<BosTmComment> comments = bosTmCommentMapper.selectBosTmCommentWithUnSync();
        List<Long> syncComments = new ArrayList<>();
        List<Long> unSyncComments = new ArrayList<>();
        if (! CollectionUtils.isEmpty(comments)) {
            List<PmsProductModel> productModels = pmsCommentMapper.getProductModel();
            Map<String, PmsProductModel> productModelMap = productModels.stream().collect(Collectors.toMap(PmsProductModel::getProductSn, Function.identity(), (key1, key2) -> key2));
            List<PmsComment> lastList = comments.stream().reduce(new ArrayList<PmsComment>(1000),(list, obj)->{
                if (! oConvertUtils.isEmpty(productModelMap.get(obj.getProductcode()))) {
                    PmsComment comment = new PmsComment();
                    comment.setProductId(productModelMap.get(obj.getProductcode()).getId());
                    comment.setMemberNickName(obj.getUsernick());
                    comment.setProductName(productModelMap.get(obj.getProductcode()).getName());
                    comment.setStar(5);
                    comment.setCreateTime(obj.getCreated());
                    comment.setShowStatus("0");
                    comment.setContent(obj.getContent());
                    comment.setMemberId(1000L);
                    comment.setSourceType("tianmao");
                    comment.setSourceId(obj.getId().toString());
                    list.add(comment);
                    syncComments.add(obj.getId());
                } else {
                    unSyncComments.add(obj.getId());
                }
                if (list.size()==1000){
                    List<String> sourceIds = list.stream().map(PmsComment::getSourceId).collect(Collectors.toList());
                    List<String> dbSourceIds = pmsCommentMapper.checkingForDuplicate(sourceIds);
                    if (dbSourceIds.size() > 0) {
                        list.removeAll(list.stream().filter(m->dbSourceIds.contains(m.getSourceId())).collect(Collectors.toList()));
                    }
                    this.saveBatch(list);
                    list = new ArrayList<PmsComment>(1000);
                }
                return list;
            }, (list1, list2)->{
                list1.addAll(list2);
                return list1;
            });
            if (lastList.size()>0){
                List<String> lastSourceIds = lastList.stream().map(PmsComment::getSourceId).collect(Collectors.toList());
                List<String> lastDbSourceIds = pmsCommentMapper.checkingForDuplicate(lastSourceIds);
                if (lastDbSourceIds.size() > 0) {
                    lastList.removeAll(lastList.stream().filter(m->lastDbSourceIds.contains(m.getSourceId())).collect(Collectors.toList()));
                }
                this.saveBatch(lastList);
            }
            StringBuilder updateSyncUrl = new StringBuilder();
            updateSyncUrl.append(ApiUtil.getSyncUrl());
            updateSyncUrl.append("g/comment/updateBatch");
            log.info("updateSyncUrl:" + updateSyncUrl.toString());

            Map<String, String> headers = new HashMap<>();
            headers.put("content-type", "application/json;charset=UTF-8");


            //处理同步成功的
            if (! CollectionUtils.isEmpty(syncComments)) {
                Map<String,Object> syncParams = new HashMap<>();
                //JSONObject syncParams = new JSONObject();
                syncParams.put("ids", StringUtils.join(syncComments, ","));
                syncParams.put("isSync", 1);
                String syncResult = HttpUtil.postRequest(updateSyncUrl.toString(), syncParams);

                /*List<Long> lastSyncList = syncComments.stream().reduce(new ArrayList<Long>(1000),(list, obj)->{
                    list.add(obj);
                    if (list.size()==1000){
                        bosTmCommentMapper.updateBatch(list,1);
                        list = new ArrayList<Long>(1000);
                    }
                    return list;
                }, (list1, list2)->{
                    list1.addAll(list2);
                    return list1;
                });
                if (lastSyncList.size()>0){
                    bosTmCommentMapper.updateBatch(lastSyncList,1);
                }*/
            }
            //处理同步失败的
            if (! CollectionUtils.isEmpty(unSyncComments)) {
                Map<String,Object> unSyncParams = new HashMap<>();
                //JSONObject unSyncParams = new JSONObject();
                unSyncParams.put("ids", StringUtils.join(unSyncComments, ","));
                unSyncParams.put("isSync", -1);
                String unSyncResult = HttpUtil.postRequest(updateSyncUrl.toString(), unSyncParams);

                /*List<Long> lastUnSyncList = unSyncComments.stream().reduce(new ArrayList<Long>(1000),(list, obj)->{
                    list.add(obj);
                    if (list.size()==1000){
                        bosTmCommentMapper.updateBatch(list,-1);
                        list = new ArrayList<Long>(1000);
                    }
                    return list;
                }, (list1, list2)->{
                    list1.addAll(list2);
                    return list1;
                });
                if (lastUnSyncList.size()>0){
                    bosTmCommentMapper.updateBatch(lastUnSyncList,-1);
                }*/
            }
        }
    }
}
